﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.JScript.Compiler;
using Microsoft.JScript.Compiler.ParseTree;

namespace Yuyi.PluginForJS.Addin
{
    public static class Helper
    {
        public static IList<AbstractNode> CreateNodes(DList<Statement, BlockStatement> statements)
        {
            DList<Statement, BlockStatement>.Iterator iterator = new DList<Statement, BlockStatement>.Iterator(statements);
            IList<AbstractNode> nodes = new List<AbstractNode>();
            while (iterator.Element != null)
            {
                Statement statement = iterator.Element;
                if (statement != null)
                {
                    IList<AbstractNode> childNodes = CreateNodes(statement);
                    if (childNodes != null && childNodes.Count > 0)
                    {
                        foreach (AbstractNode node in childNodes)
                        {
                            nodes.Add(node);
                        }
                    }
                }
                iterator.Advance();
            }

            return nodes;
        }

        private static IList<AbstractNode> CreateNodes(Statement statement)
        {
            if (statement == null) return null;
            IList<AbstractNode> nodes = new List<AbstractNode>();
            switch (statement.Opcode)
            {
                case Statement.Operation.Function:
                    FunctionStatement functionStatement = statement as FunctionStatement;
                    IFunctionStrategy strategyStatement = new FunctionStatementStrategy(functionStatement);
                    nodes.Add(new FunctionNode(strategyStatement, null));
                    break;
                case Statement.Operation.VariableDeclaration:
                    VariableDeclarationStatement variableDeclarationStatement = statement as VariableDeclarationStatement;
                    foreach (VariableDeclarationListElement element in variableDeclarationStatement.Declarations)
                    {
                        InitializerVariableDeclaration variableDeclaration = element.Declaration as InitializerVariableDeclaration;
                        if (variableDeclaration != null)
                        {
                            if (variableDeclaration.Initializer is FunctionExpression)
                            {
                                IFunctionStrategy strategyExpression = new FunctionExpressionStrategy(variableDeclaration.Initializer);
                                nodes.Add(new FunctionNode(strategyExpression, variableDeclaration.Name.Spelling));
                            }
                        }
                    }
                    break;
            }
            return nodes;
        }
    }
}